package com.suning.sawp.service.impl.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.suning.framework.dal.client.DalClient;
import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.dto.storeman.Category;
import com.suning.sawp.intf.model.ModelAnalyseService;
import com.suning.sawp.intf.model.dto.ModelAnalyseDto;
import com.suning.sawp.intf.model.dto.ModelRecommendDto;
import com.suning.sawp.intf.model.dto.SaleAnalyseDto;
import com.suning.sawp.intf.model.vo.ContributionCompareResponse;
import com.suning.sawp.intf.model.vo.ContributionCompareVo;
import com.suning.sawp.intf.model.vo.ContributionResponse;
import com.suning.sawp.intf.model.vo.ContributionVo;
import com.suning.sawp.intf.model.vo.ModelRecommendResponse;
import com.suning.sawp.intf.model.vo.ModelRecommendVo;
import com.suning.sawp.intf.model.vo.ModelTopResponse;
import com.suning.sawp.intf.model.vo.ModelTopVo;
import com.suning.sawp.intf.model.vo.ModelValidResponse;
import com.suning.sawp.intf.model.vo.ModelValidVo;
import com.suning.sawp.intf.model.vo.SummaryContributionVo;
import com.suning.sawp.service.util.DJStringUtils;

/**
 * 样机分析服务实现
 *
 * @author 15050519
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class ModelAnalyseServiceImpl implements ModelAnalyseService {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

    /**
     * 数值0
     */
    private static final int ZERO = 0;

    /**
     * 数值5-店长推荐品类下商品总数最多5条
     */
    private static final int FIVE = 5;

    /**
     * 数据库操作对象
     */
    @Resource
    DalClient dalClient;

    /**
     * 保存门店样机销售数据
     */
    @Override
    public void saveModelAnalyse(ModelAnalyseDto dto) {
        LOGGER.info("saveModelAnalyse enter, dto={}", dto);
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("disCode", dto.getDisCode());
        queryMap.put("disName", dto.getDisName());
        queryMap.put("orgCode", dto.getOrgCode());
        queryMap.put("orgName", dto.getOrgName());
        queryMap.put("storeCode", dto.getStoreCode());
        queryMap.put("storeName", dto.getStoreName());
        queryMap.put("storeType", dto.getStoreType());
        queryMap.put("cateCode", dto.getCateCode());
        queryMap.put("cateName", dto.getCateName());
        queryMap.put("branchCode", dto.getBranchCode());
        queryMap.put("branchName", dto.getBranchName());
        queryMap.put("saleNum", null != dto.getSaleNum() ? dto.getSaleNum() : 0);
        queryMap.put("saleAmount", StringUtils.isNotBlank(dto.getSaleAmount()) ? dto.getSaleAmount() : "0.0");
        queryMap.put("validNum", null != dto.getValidNum() ? dto.getValidNum() : 0);
        if (null != dto.getUpdateTime()) {
            queryMap.put("updateTime", dto.getUpdateTime());
        } else {
            queryMap.put("updateTime", new Date());
        }
        // 保存数据库
        dalClient.execute("MODEL_ANALYSE.SAVE_MODE", queryMap);
        LOGGER.info("saveModelAnalyse exit, dto={}", dto);
    }

    /**
     * 保存门店销售数据 不区分样机，非样机
     */
    @Override
    public void saveSaleAnalyse(SaleAnalyseDto dto) {
        LOGGER.info("saveSaleAnalyse enter, dto={}", dto);
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("disCode", dto.getDisCode());
        queryMap.put("disName", dto.getDisName());
        queryMap.put("orgCode", dto.getOrgCode());
        queryMap.put("orgName", dto.getOrgName());
        queryMap.put("storeCode", dto.getStoreCode());
        queryMap.put("storeName", dto.getStoreName());
        queryMap.put("storeType", dto.getStoreType());
        queryMap.put("cateCode", dto.getCateCode());
        queryMap.put("cateName", dto.getCateName());
        queryMap.put("branchCode", dto.getBranchCode());
        queryMap.put("branchName", dto.getBranchName());
        queryMap.put("saleNum", null != dto.getSaleNum() ? dto.getSaleNum() : 0);
        queryMap.put("saleAmount", StringUtils.isNotBlank(dto.getSaleAmount()) ? dto.getSaleAmount() : "0.0");
        if (null != dto.getUpdateTime()) {
            queryMap.put("updateTime", dto.getUpdateTime());
        } else {
            queryMap.put("updateTime", new Date());
        }
        // 保存数据库
        dalClient.execute("MODEL_ANALYSE.SAVE_STORE", queryMap);
        LOGGER.info("saveSaleAnalyse exit, dto={}", dto);
    }

    /**
     * 查询门店汇总贡献率
     */
    @Override
    public List<SummaryContributionVo> querySummaryContribution(String storeCode, List<Category> cates) {
        LOGGER.info("querySummaryContribution enter, storeCode={}", storeCode);
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("storeCode", storeCode);
        // 督导品类不为空
        if (CollectionUtils.isNotEmpty(cates)) {
            // 转换参数类型
            List<String> list = Lists.transform(cates, new Function<Category, String>() {
                @Override
                public String apply(Category input) {
                    return input.getCategoryCode();
                }
            });
            queryMap.put("cateCodes", list);
        }
        // 查询样机销售额
        List<SummaryContributionVo> modelSale = dalClient.queryForList("MODEL_ANALYSE.QUERY_MODEL_SUMMARY_CONTRIBUTION",
                queryMap, SummaryContributionVo.class);
        // 查询门店总销售额
        List<SummaryContributionVo> storeSale = dalClient.queryForList("MODEL_ANALYSE.QUERY_STORE_SUMMARY_CONTRIBUTION",
                queryMap, SummaryContributionVo.class);
        // 返回样机贡献率
        List<SummaryContributionVo> result = convertSummaryContribution(modelSale, storeSale);
        // 店长查询时
        if (CollectionUtils.isEmpty(cates)) {
            // 结果为空时,返回默认值
            if (CollectionUtils.isEmpty(result)) {
                result = defaultSummaryContribution();
            }
            LOGGER.debug("queryContributionOfMonth result={},storeCode={}", JSON.toJSONString(result), storeCode);
        } else {
            // 转换督导品类贡献率
            result = convertSummary(result, cates);
            LOGGER.debug("queryContributionOfMonth result={},storeCode={},cateCode={}", JSON.toJSONString(result),
                    storeCode, JSON.toJSONString(cates));
        }
        return result;
    }

    /**
     * 督导品类没有销售数据时，返回默认数据
     *
     * @param summ
     * @param cates
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<SummaryContributionVo> convertSummary(List<SummaryContributionVo> summ, List<Category> cates) {
        LOGGER.info("convertSummary enter");
        List<SummaryContributionVo> list = new ArrayList<SummaryContributionVo>();
        SummaryContributionVo vo = null;
        Map<String, SummaryContributionVo> mappedDiscode = null;
        // 判断结果是否为空
        if (CollectionUtils.isNotEmpty(summ)) {
            mappedDiscode = Maps.uniqueIndex(summ, new Function<SummaryContributionVo, String>() {
                public String apply(SummaryContributionVo from) {
                    return from.getCateCode();
                }
            });
        } else {
            // 默认空集合
            mappedDiscode = new HashMap<String, SummaryContributionVo>();
        }
        for (Category cate : cates) {
            // 取是否存在该品类数据
            vo = mappedDiscode.get(cate.getCategoryCode());
            // 不存在,默认0
            if (null == vo) {
                vo = new SummaryContributionVo();
                vo.setCateCode(cate.getCategoryCode());
                vo.setCateName(cate.getCategoryName());
                vo.setSaleAmount("0.00");
                vo.setRate("0.0");
            }
            list.add(vo);
        }
        return list;
    }

    /**
     * 转换汇总贡献率对象
     *
     * @param modelSale
     * @param storeSale
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<SummaryContributionVo> convertSummaryContribution(List<SummaryContributionVo> modelSale,
            List<SummaryContributionVo> storeSale) {
        LOGGER.info("convertSummaryContribution enter");
        // 门店销售不为空时
        if (CollectionUtils.isNotEmpty(storeSale)) {
            for (SummaryContributionVo vo : storeSale) {
                // 重新组装对象
                setSummaryContribution(vo, modelSale);
            }
            return storeSale;
        }
        // 返回默认数组对象
        return Collections.emptyList();
    }

    /**
     * 默认店长汇总信息设置
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<SummaryContributionVo> defaultSummaryContribution() {
        LOGGER.info("defaultSummaryContribution enter");
        List<SummaryContributionVo> summary = new ArrayList<SummaryContributionVo>();
        SummaryContributionVo vo = new SummaryContributionVo();
        // 默认都是0
        vo.setRate("0.0");
        vo.setSaleAmount("0.00");
        vo.setTotalAmount("0.00");
        summary.add(vo);
        return summary;
    }

    /**
     * 对单个门店汇总数据转换
     *
     * @param vo
     * @param modelSale
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private void setSummaryContribution(SummaryContributionVo vo, List<SummaryContributionVo> modelSale) {
        LOGGER.info("setSummaryContribution enter");
        if (CollectionUtils.isNotEmpty(modelSale)) {
            SummaryContributionVo model = getSummaryContributionVo(vo.getCateCode(), modelSale);
            // 没有品类信息,说明是店长
            if (null != model) {
                // 金额保留两位小数
                vo.setSaleAmount(DJStringUtils.getTwoScale(model.getSaleAmount()));
                vo.setTotalAmount(DJStringUtils.getTwoScale(vo.getTotalAmount()));
                vo.setRate(DJStringUtils.calculateRateString(model.getSaleAmount(), vo.getTotalAmount()));
                return;
            }
        }
        // 不存在匹配数据,设置默认数值
        vo.setSaleAmount("0.00");
        vo.setRate("0.0");
        // 金额保留两位小数
        vo.setTotalAmount(DJStringUtils.getTwoScale(vo.getTotalAmount()));
    }

    /**
     * 根据匹配查询样机销售数据
     *
     * @param cateCode
     * @param modelSale
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private SummaryContributionVo getSummaryContributionVo(String cateCode, List<SummaryContributionVo> modelSale) {
        LOGGER.info("getSummaryContributionVo enter");
        // 存在品类时
        if (StringUtils.isNotBlank(cateCode)) {
            for (SummaryContributionVo vo : modelSale) {
                // 利用品类匹配数据
                if (cateCode.equals(vo.getCateCode())) {
                    return vo;
                }
            }
            return null;
        } else {
            // 返回第一条数据
            return modelSale.get(ZERO);
        }
    }

    /**
     * 查询门店品类，品牌贡献率 店长查看品类<br>
     * 品牌贡献率 督导查看品牌贡献率
     */
    @Override
    public ContributionResponse queryContributionOfMonth(String storeCode, String cateCode) {
        LOGGER.info("queryContributionOfMonth enter, storeCode={},cateCode={}", storeCode, cateCode);
        ContributionResponse resp = new ContributionResponse();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("storeCode", storeCode);
        // 判断品类是否为空
        if (StringUtils.isNotBlank(cateCode)) {
            queryMap.put("cateCode", cateCode);
        }
        // 查询样机销售额
        List<ContributionVo> modelSale = dalClient.queryForList("MODEL_ANALYSE.QUERY_MODEL_CONTRIBUTION", queryMap,
                ContributionVo.class);
        // 查询门店总销售额
        List<ContributionVo> storeSale = dalClient.queryForList("MODEL_ANALYSE.QUERY_STORE_CONTRIBUTION", queryMap,
                ContributionVo.class);
        // 处理品类,品牌贡献率
        List<ContributionVo> result = convertContribution(modelSale, storeSale, cateCode);
        // 结果
        resp.setList(result);
        LOGGER.debug("queryContributionOfMonth resp={},storeCode={},cateCode={}", resp, storeCode, cateCode);
        return resp;
    }

    /**
     * 
     * 转换品类，品牌贡献率
     * 
     * @param modelSale
     * @param storeSale
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ContributionVo> convertContribution(List<ContributionVo> modelSale, List<ContributionVo> storeSale,
            String cateCode) {
        LOGGER.info("convertContribution enter");
        // 门店销售不为空时
        if (CollectionUtils.isNotEmpty(storeSale)) {
            ContributionVo model = null;
            String ytotal = "0";
            String dtotal = "0";
            for (ContributionVo vo : storeSale) {
                // 判断品类编码是否为空
                if (StringUtils.isBlank(cateCode)) {
                    // 门店品类累计销售额
                    dtotal = DJStringUtils.addition(dtotal, vo.getSaleAmount());
                    // 取品类样机
                    model = getContributionByCateCode(vo.getCateCode(), modelSale);
                    // 样机累计销售额
                    ytotal = null == model ? ytotal : DJStringUtils.addition(ytotal, model.getSaleAmount());
                } else {
                    // 取品牌样机
                    model = getContributionByBranchCode(vo.getBranchCode(), modelSale);
                }
                // 样机销售不为空时
                if (null != model) {
                    // 计算贡献率
                    vo.setRate(DJStringUtils.calculateRateDouble(model.getSaleAmount(), vo.getSaleAmount()));
                    // 保留两位小数
                    vo.setSaleAmount(DJStringUtils.getTwoScale(model.getSaleAmount()));
                } else {
                    // 默认贡献率
                    vo.setRate(0D);
                    // 默认销售额
                    vo.setSaleAmount("0.00");
                }
            }
            // 非样机部分
            if (StringUtils.isBlank(cateCode)) {
                ContributionVo vo = new ContributionVo();
                vo.setCateCode("-1");
                vo.setCateName("非样机");
                // 非样机销售额
                String saleAmount = DJStringUtils.subtraction(dtotal, ytotal);
                vo.setSaleAmount(saleAmount);
                // 非样机贡献率
                vo.setRate(DJStringUtils.calculateRateDouble(saleAmount, dtotal));
                storeSale.add(vo);
            }
            // 按照贡献率排序, 由高到低
            Collections.sort(storeSale, new Comparator<ContributionVo>() {
                @Override
                public int compare(ContributionVo o1, ContributionVo o2) {
                    if( o2.getRate() == null){
                        return -1;  
                    }
                    
                    if( o1.getRate() == null){
                        return 1;  
                    }
                    // 降序
                    return o2.getRate().compareTo(o1.getRate());
                }
            });
            return storeSale;
        }
        // 默认空集合
        return Collections.emptyList();
    }

    /**
     * 根据品类取样机销售
     *
     * @param cateCode
     * @param modelSale
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private ContributionVo getContributionByCateCode(String cateCode, List<ContributionVo> modelSale) {
        LOGGER.info("getContributionByCateCode enter");
        if (StringUtils.isNotBlank(cateCode) && CollectionUtils.isNotEmpty(modelSale)) {
            for (ContributionVo model : modelSale) {
                if (cateCode.equals(model.getCateCode())) {
                    return model;
                }
            }
        }
        return null;
    }

    /**
     * 根据品牌取样机销售
     *
     * @param branchCode
     * @param modelSale
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private ContributionVo getContributionByBranchCode(String branchCode, List<ContributionVo> modelSale) {
        LOGGER.info("getContributionByBranchCode enter");
        if (StringUtils.isNotBlank(branchCode) && CollectionUtils.isNotEmpty(modelSale)) {
            for (ContributionVo model : modelSale) {
                if (branchCode.equals(model.getBranchCode())) {
                    return model;
                }
            }
        }
        return null;
    }

    /**
     * 查询品类，品牌下有效样机率
     */
    @Override
    public ModelValidResponse queryModelValid(String storeCode, String cateCode) {
        LOGGER.info("queryModelValid enter, storeCode={},cateCode={}", storeCode, cateCode);
        ModelValidResponse resp = new ModelValidResponse();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("storeCode", storeCode);
        // 判断品类是否为空
        if (StringUtils.isNotBlank(cateCode)) {
            queryMap.put("cateCode", cateCode);
        }
        // 查询品类下有效样机
        List<ModelValidVo> modelSale = dalClient.queryForList("MODEL_ANALYSE.QUERY_MODEL_VALID", queryMap,
                ModelValidVo.class);
        // 查询门店品类下有效样机总数
        List<ModelValidVo> storeSale = dalClient.queryForList("MODEL_ANALYSE.QUERY_STORE_C_VALID", queryMap,
                ModelValidVo.class);
        // 处理品类有效样机率
        List<ModelValidVo> storeSaleResult = new ArrayList<ModelValidVo>();

        for(ModelValidVo store : storeSale){
            if (StringUtils.isBlank(cateCode)) {
                String cateName = ConfigConstants.DEFAULT_CATE_MAP.get(store.getCateCode());
                if(StringUtils.isBlank(cateName)){
                    continue;
                }else{
                    storeSaleResult.add(store);
                }
            }else{
                storeSaleResult.add(store);
            }
        }
    

        List<ModelValidVo> result = convertModelValid(modelSale, storeSaleResult, cateCode);
        // 结果
        resp.setList(result);
        LOGGER.debug("queryModelValid resp={},storeCode={},cateCode={}", resp, storeCode, cateCode);
        return resp;
    }

    /**
     * 
     * 转换有效样机率对象
     * 
     * @param modelSale
     * @param storeSale
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ModelValidVo> convertModelValid(List<ModelValidVo> modelSale, List<ModelValidVo> storeSale,
            String cateCode) {
        LOGGER.info("convertModelValid enter");
        if (CollectionUtils.isNotEmpty(storeSale)) {
            ModelValidVo model = null;
            for (ModelValidVo store : storeSale) {
                if (StringUtils.isBlank(cateCode)) {
                    // 取品类有效样机
                    model = getModelValidByCateCode(store.getCateCode(), modelSale);
                } else {
                    // 取品牌有效样机
                    model = getModelValidByBranchCode(store.getBranchCode(), modelSale);
                }
                if (null != model) {
                    // 计算有效样机率
                    store.setRate(DJStringUtils.calculateRateDouble(model.getValidNum().toString(),
                            store.getTotalNum().toString()));
                    // 设置样机有效数
                    store.setValidNum(model.getValidNum());
                } else {
                    // 默认有效样机率
                    store.setRate(0D);
                    store.setValidNum(Integer.valueOf("0"));
                }
            }
            // 按照有效样机率排序, 由高到低
            Collections.sort(storeSale, new Comparator<ModelValidVo>() {
                @Override
                public int compare(ModelValidVo o1, ModelValidVo o2) {
                    // 降序
                    if( o2.getRate() == null){
                        return -1;  
                    }
                    
                    if( o1.getRate() == null){
                        return 1;  
                    }
                    
                    return o2.getRate().compareTo(o1.getRate());
                }
            });
            return storeSale;
        }
        // 默认空集合
        return Collections.emptyList();
    }

    /**
     * 
     * 根据品牌取品牌有效样机
     * 
     * @param branchCode
     * @param modelSale
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private ModelValidVo getModelValidByBranchCode(String branchCode, List<ModelValidVo> modelSale) {
        LOGGER.info("getModelValidByBranchCode enter");
        if (StringUtils.isNotBlank(branchCode) && CollectionUtils.isNotEmpty(modelSale)) {
            for (ModelValidVo model : modelSale) {
                if (branchCode.equals(model.getBranchCode())) {
                    return model;
                }
            }
        }
        return null;
    }

    /**
     * 
     * 根据品类取品类的有效样机
     * 
     * @param cateCode
     * @param modelSale
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private ModelValidVo getModelValidByCateCode(String cateCode, List<ModelValidVo> modelSale) {
        LOGGER.info("getModelValidByCateCode enter");
        if (StringUtils.isNotBlank(cateCode) && CollectionUtils.isNotEmpty(modelSale)) {
            for (ModelValidVo model : modelSale) {
                if (cateCode.equals(model.getCateCode())) {
                    return model;
                }
            }
        }
        return null;
    }

    /**
     * 查询某大区下同级别门店同期贡献率比较
     */
    @Override
    public ContributionCompareResponse queryContributionCompare(String disCode, String storeType, String cateCode,
            StoreManDto storeMan) {
        LOGGER.info("queryContributionCompare enter,disCode={},storeType={},cateCode={}", disCode, storeType, cateCode);
        ContributionCompareResponse resp = new ContributionCompareResponse();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("disCode", StringUtils.isNotBlank(disCode) ? disCode : "");
        queryMap.put("storeType", StringUtils.isNotBlank(storeType) ? storeType : "");
        if (StringUtils.isNotBlank(cateCode)) {
            queryMap.put("cateCode", cateCode);
        }
        List<ContributionCompareVo> list = new ArrayList<ContributionCompareVo>();
        // 查询门店样机销售额
        List<ModelAnalyseDto> modelSale = dalClient.queryForList("MODEL_ANALYSE.QUERY_MODEL_CONTRIBUTION_COMPARE",
                queryMap, ModelAnalyseDto.class);
        // 查询门店总销售额
        List<SaleAnalyseDto> storeSale = dalClient.queryForList("MODEL_ANALYSE.QUERY_STORE_CONTRIBUTION_COMPARE",
                queryMap, SaleAnalyseDto.class);
        // 判断店铺销售是否为空
        if (CollectionUtils.isNotEmpty(storeSale)) {
            ContributionCompareVo compare = null;
            ModelAnalyseDto model = null;
            boolean isExist = false;
            for (SaleAnalyseDto sale : storeSale) {
                compare = new ContributionCompareVo();
                compare.setStoreCode(sale.getStoreCode());
                compare.setStoreName(sale.getStoreName());
                // 获取门店样机
                model = getModelAnalyse(sale.getStoreCode(), modelSale);
                if (null != model) {
                    // 计算门店贡献率
                    compare.setRate(DJStringUtils.calculateRateDouble(model.getSaleAmount(), sale.getSaleAmount()));
                } else {
                    // 默认贡献率0
                    compare.setRate(0D);
                }
                // 判断本门店是否存在销售记录
                if (sale.getStoreCode().equals(storeMan.getStoreCode())) {
                    isExist = true;
                }
                list.add(compare);
            }
            // 不存在记录,则添加默认0
            if (!isExist) {
                // 添加本门店数据, 默认0
                ContributionCompareVo defaultContribution = new ContributionCompareVo();
                defaultContribution.setStoreCode(storeMan.getStoreCode());
                defaultContribution.setStoreName(storeMan.getStoreName());
                defaultContribution.setRate(0D);
                list.add(defaultContribution);
            }
            // 按照贡献率排序, 由高到低
            Collections.sort(list, new Comparator<ContributionCompareVo>() {
                @Override
                public int compare(ContributionCompareVo o1, ContributionCompareVo o2) {
                    if( o2.getRate() == null){
                        return -1;  
                    }
                    
                    if( o1.getRate() == null){
                        return 1;  
                    }
                    // 降序
                    return o2.getRate().compareTo(o1.getRate());
                }
            });
        } else {
            // 添加本门店数据, 默认0
            ContributionCompareVo compare = new ContributionCompareVo();
            compare.setStoreCode(storeMan.getStoreCode());
            compare.setStoreName(storeMan.getStoreName());
            compare.setRate(0D);
            list.add(compare);
        }
        // 设置返回结果
        resp.setList(list);
        LOGGER.debug("queryContributionCompare resp={},cateCode={}", resp, cateCode);
        return resp;
    }

    /**
     * 去除门店样机贡献对象
     *
     * @param storeCode
     * @param modelSale
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private ModelAnalyseDto getModelAnalyse(String storeCode, List<ModelAnalyseDto> modelSale) {
        LOGGER.info("getModelAnalyse enter");
        if (StringUtils.isNotBlank(storeCode) && CollectionUtils.isNotEmpty(modelSale)) {
            for (ModelAnalyseDto model : modelSale) {
                if (storeCode.equals(model.getStoreCode())) {
                    return model;
                }
            }
        }
        return null;
    }

    /**
     * 查询门店样机销售TOP 前20，后20
     */
    @Override
    public ModelTopResponse queryModelTopTwenty(String storeCode, String cateCode, String flag) {
        LOGGER.info("queryModelTopTwenty enter,storeCode={},cateCode={},flag={}", storeCode, cateCode, flag);
        ModelTopResponse resp = new ModelTopResponse();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("storeCode", storeCode);
        queryMap.put("flag", flag);
        if (StringUtils.isNotBlank(cateCode)) {
            queryMap.put("cateCode", cateCode);
        }
        // 查询门店TOP排行
        List<ModelTopVo> result = dalClient.queryForList("MODEL_ANALYSE.QUERY_MODEL_TOP", queryMap, ModelTopVo.class);
        // 结果
        resp.setList(result);
        LOGGER.debug("queryModelTopTwenty resp={},storeCode={},cateCode={},flag={}", resp, storeCode, cateCode, flag);
        return resp;
    }

    /**
     * 查询门店样机推荐
     */
    @Override
    public ModelRecommendResponse queryModelRecommend(String storeCode, String cateCode) {
        LOGGER.info("queryModelRecommend enter,storeCode={},cateCode={}", storeCode, cateCode);
        ModelRecommendResponse resp = new ModelRecommendResponse();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("storeCode", storeCode);
        if (StringUtils.isNotBlank(cateCode)) {
            queryMap.put("cateCode", cateCode);
        }
        List<ModelRecommendVo> list = null;
        // 查询门店样机推荐
        List<ModelRecommendDto> result = dalClient.queryForList("MODEL_ANALYSE.QUERY_MODEL_RECOMMEND", queryMap,
                ModelRecommendDto.class);
        // 判断品类是否存在, 确定是店长(没有品类), 还是督导(有品类)
        if (StringUtils.isNotBlank(cateCode)) {
            list = convertRecommend(result);
        } else {
            // 店长分品类返回每个品类下最多5条推荐
            //时方案，不根据品类分组，每个品类取前五，根据所有单品销量倒序
            list = resetRecommendNew(result);
//            list = resetRecommend(result);
        }
        // 结果
        resp.setList(list);
        LOGGER.debug("queryModelRecommend resp={},storeCode={},cateCode={}", resp, storeCode, cateCode);
        return resp;
    }

    /**
     * 组装推荐商品
     *
     * @param result
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ModelRecommendVo> convertRecommend(List<ModelRecommendDto> result) {
        LOGGER.info("convertRecommend enter");
        if (CollectionUtils.isNotEmpty(result)) {
            ModelRecommendVo vo = null;
            List<ModelRecommendVo> list = new ArrayList<ModelRecommendVo>();
            for (ModelRecommendDto dto : result) {
                vo = new ModelRecommendVo();
                vo.setCommCode(dto.getCommCode());
                vo.setCommName(dto.getCommName());
                vo.setSaleNum(dto.getSaleNum());
                list.add(vo);
            }
            return list;
        }
        return Collections.emptyList();
    }

    /**
     * 组装店长品类下推荐商品 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param result
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ModelRecommendVo> resetRecommend(List<ModelRecommendDto> result) {
        LOGGER.info("resetRecommend enter");
        if (CollectionUtils.isNotEmpty(result)) {
            ModelRecommendVo vo = null;
            List<ModelRecommendVo> list = null;
            Map<String, List<ModelRecommendVo>> map = new HashMap<String, List<ModelRecommendVo>>();
            // 循环处理品类下的商品
            for (ModelRecommendDto dto : result) {
                list = map.get(dto.getCateCode());
                // 判断该品类下集合是否存在
                if (null == list) {
                    // 不存在则新增集合保存数据
                    list = new ArrayList<ModelRecommendVo>();
                }
                // 每个品类返回最多5条数据
                if (list.size() >= FIVE) {
                    continue;
                }
                // 封装新结果对象
                vo = new ModelRecommendVo();
                vo.setCommCode(dto.getCommCode());
                vo.setCommName(dto.getCommName());
                vo.setSaleNum(dto.getSaleNum());
                // 放进集合中
                list.add(vo);
                // 将品类放进map中处理
                map.put(dto.getCateCode(), list);
            }

            // 新建新的结果对象
            list = new ArrayList<ModelRecommendVo>();
            // 将品类下商品合并,并返回
            for (List<ModelRecommendVo> param : map.values()) {
                list.addAll(param);
            }
            return list;
        }
        return Collections.emptyList();
    }
    
    /**
     * 临时方案，不根据品类分组，每个品类取前五，根据所有单品销量倒序
     *
     * @param result
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ModelRecommendVo> resetRecommendNew(List<ModelRecommendDto> result) {
        LOGGER.info("resetRecommendNewS enter");
        if (CollectionUtils.isNotEmpty(result)) {
            ModelRecommendVo vo = null;
            Map<String, List<ModelRecommendVo>> map = new HashMap<String, List<ModelRecommendVo>>();
            // 新建新的结果对象
            List<ModelRecommendVo> allList = new ArrayList<ModelRecommendVo>();
            // 循环处理品类下的商品
            for (ModelRecommendDto dto : result) {
                List<ModelRecommendVo> list = null;
                list = map.get(dto.getCateCode());
                // 判断该品类下集合是否存在
                if (null == list) {
                    // 不存在则新增集合保存数据
                    list = new ArrayList<ModelRecommendVo>();
                }
                // 每个品类返回最多5条数据
                if (list.size() >= FIVE) {
                    continue;
                }
                // 封装新结果对象
                vo = new ModelRecommendVo();
                vo.setCommCode(dto.getCommCode());
                vo.setCommName(dto.getCommName());
                vo.setSaleNum(dto.getSaleNum());
                // 放进集合中
                list.add(vo);
                allList.add(vo);
                // 将品类放进map中处理
                map.put(dto.getCateCode(), list);
            }

            return allList;
        }
        return Collections.emptyList();
    }
}
